<template>
    <div class="navbar">
        <div class="navbar-left">
            <!-- 桌面端折叠按钮 -->
            <el-button class="collapse-btn desktop-only" :icon="isCollapse ? Expand : Fold" @click="toggleCollapse" circle
                size="small" type="text" />
            
            <!-- 移动端汉堡菜单按钮 -->
            <el-button class="mobile-menu-btn mobile-only" @click="toggleMobileMenu" circle size="small" type="text">
                <el-icon><Menu /></el-icon>
            </el-button>
            
            <el-breadcrumb separator="/" class="navbar-breadcrumb">
                <el-breadcrumb-item v-for="(item, idx) in breadcrumbList" :key="idx" :to="item.to">{{ item.name
                    }}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="navbar-actions">
            <el-popover
              placement="bottom"
              width="350"
              trigger="click"
              v-model:visible="showNotification"
            >
              <div class="notification-popover">
                <div class="notification-tabs">
                  <span :class="{active: activeTab==='notice'}" @click="activeTab='notice'">
                    通知
                    <el-badge :value="55" class="tab-badge" />
                  </span>
                  <span :class="{active: activeTab==='message'}" @click="activeTab='message'">
                    私信
                    <el-badge :value="3" class="tab-badge" />
                  </span>
                </div>
                <div class="notification-content">
                  <div v-if="activeTab==='notice'">
                    <ul class="notice-list">
                      <li class="notice-item">
                        <span class="notice-title">系统更新通知</span>
                        <span class="notice-time">1分钟前</span>
                      </li>
                      <li class="notice-item">
                        <span class="notice-title">有新的用户注册</span>
                        <span class="notice-time">5分钟前</span>
                      </li>
                      <li class="notice-item">
                        <span class="notice-title">服务器重启成功</span>
                        <span class="notice-time">10分钟前</span>
                      </li>
                    </ul>
                  </div>
                  <div v-else>
                    暂无新消息
                  </div>
                </div>
                <div class="notification-footer">
                  <a href="#">查看全部</a>
                </div>
              </div>
              <template #reference>
                <el-badge :value="58" class="navbar-badge">
                  <el-icon style="cursor:pointer;"><Bell /></el-icon>
                </el-badge>
              </template>
            </el-popover>
            <el-dropdown>
                <div class="navbar-user-info">
                    <div class="navbar-avatar">
                        <el-avatar :size="32" :src="avatar" />
                    </div>
                    <div class="user-info">
                        <span class="username">{{ userInfo.userName || '用户' }}</span>
                        <span class="roles" :class="roleClass">{{ userRoles }}</span>
                    </div>
                </div>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item @click="goProfile">个人中心</el-dropdown-item>
                        <el-dropdown-item @click="openChangePasswordDialog">修改密码</el-dropdown-item>
                        <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
        
        <!-- 移动端导航菜单 -->
        <div class="mobile-nav-menu" v-if="showMobileMenu" @click="closeMobileMenu">
            <div class="mobile-nav-overlay"></div>
            <div class="mobile-nav-content" @click.stop>
                <div class="mobile-nav-header">
                    <span class="mobile-nav-title">导航菜单</span>
                    <el-button @click="closeMobileMenu" circle size="small" type="text">
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
                <div class="mobile-nav-items">
                    <div class="mobile-nav-item" @click="navigateTo('/dashboard')">
                        <el-icon><Odometer /></el-icon>
                        <span>首页</span>
                    </div>
                    <div class="mobile-nav-item" v-if="isAdmin" @click="navigateTo('/users')">
                        <el-icon><User /></el-icon>
                        <span>用户管理</span>
                    </div>
                    <div class="mobile-nav-item" v-if="isAdmin" @click="navigateTo('/role')">
                        <el-icon><User /></el-icon>
                        <span>角色管理</span>
                    </div>
                    <div class="mobile-nav-item" v-if="isAdmin" @click="navigateTo('/permission')">
                        <el-icon><Setting /></el-icon>
                        <span>权限管理</span>
                    </div>
                    <div class="mobile-nav-item" v-if="isAdmin" @click="navigateTo('/system')">
                        <el-icon><Setting /></el-icon>
                        <span>系统管理</span>
                    </div>
                    <div class="mobile-nav-item" v-if="isAdmin" @click="navigateTo('/logs')">
                        <el-icon><Document /></el-icon>
                        <span>系统日志</span>
                    </div>
                    <div class="mobile-nav-item" @click="navigateTo('/profile')">
                        <el-icon><User /></el-icon>
                        <span>个人中心</span>
                    </div>
                    <div class="mobile-nav-item" @click="navigateTo('/help')">
                        <el-icon><QuestionFilled /></el-icon>
                        <span>帮助</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    

</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { Bell, Fold, Expand, Menu, Close, Odometer, User, Setting, Document, QuestionFilled } from '@element-plus/icons-vue'
import { getLocalAvatarUrl } from '@/utils/avatar'


const routeMap = {
    '/dashboard': ['数据概览'],
    '/analysis': ['分析报表'],
    '/users': ['用户管理'],
    '/content': ['内容管理'],
    '/system': ['系统设置'],
    '/help': ['帮助中心'],
    '/role': ['角色管理'],
    '/permission': ['权限管理'],
    '/logs': ['系统日志'],
    '/files': ['文件管理'],
    '/profile': ['个人中心']
}
const avatarRefreshKey = ref(0)
const avatar = computed(() => {
  avatarRefreshKey.value // 依赖此值，变化时重新获取
  return getLocalAvatarUrl()
})

// 用户信息
const userInfo = ref({
  userName: '',
  roles: []
})

// 角色信息显示 - 按等级展示
const userRoles = computed(() => {
  if (!userInfo.value.roles || userInfo.value.roles.length === 0) {
    return '普通用户'
  }
  
  // 按优先级排序：管理员 > 超级管理员 > 普通用户
  const rolePriority = {
    '管理员': 3,
    '超级管理员': 2,
    '普通用户': 1
  }
  
  // 找到最高优先级的角色
  let highestRole = userInfo.value.roles[0]
  let highestPriority = rolePriority[highestRole] || 0
  
  for (const role of userInfo.value.roles) {
    const priority = rolePriority[role] || 0
    if (priority > highestPriority) {
      highestRole = role
      highestPriority = priority
    }
  }
  
  return highestRole || '普通用户'
})

// 角色样式类
const roleClass = computed(() => {
  const role = userRoles.value
  if (role === '管理员' || role === '超级管理员') {
    return 'role-admin'
  } else if (role === '普通用户') {
    return 'role-user'
  }
  return 'role-default'
})

// 获取用户信息
const getUserInfo = () => {
  try {
    const tokenData = localStorage.getItem('token')
    if (tokenData) {
      const parsedToken = JSON.parse(tokenData)
      const userData = parsedToken.userInfo || parsedToken.data?.userInfo || parsedToken
      if (userData) {
        userInfo.value = {
          userName: userData.userName || userData.username || '用户',
          roles: userData.roles || userData.userRoles || []
        }
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const props = defineProps({
    isCollapse: Boolean
})
const emit = defineEmits(['update:isCollapse'])

const route = useRoute()
const router = useRouter()
const breadcrumbList = computed(() => {
    const path = route.path
    const crumbs = [{ name: '首页', to: '/' }]
    if (routeMap[path]) {
        crumbs.push(...routeMap[path].map(name => ({ name })))
    }
    return crumbs
})

const showNotification = ref(false)
const activeTab = ref('notice')

const showMobileMenu = ref(false)

const isAdmin = computed(() => {
  return userInfo.value.roles.includes('管理员') || userInfo.value.roles.includes('超级管理员')
})

onMounted(async()=>{
  getUserInfo()
})

onMounted(() => {
  const avatarHandler = () => {
    avatarRefreshKey.value++
  }
  window.addEventListener('avatar-updated', avatarHandler)
  
  // 监听用户信息更新事件
  window.addEventListener('user-info-updated', () => {
    getUserInfo()
  })
  
  // 保存handler引用以便清理
  window.avatarHandler = avatarHandler
})

onUnmounted(() => {
  if (window.avatarHandler) {
    window.removeEventListener('avatar-updated', window.avatarHandler)
  }
  window.removeEventListener('user-info-updated', getUserInfo)
})

function logout() {
  const token = localStorage.getItem('token')
    if (token) {
      // 处理token逻辑
    }
    
    localStorage.removeItem('token')
    localStorage.setItem('token',JSON.stringify(token))
    
    // 不清除记住的用户信息，让用户下次登录时还能看到
    // localStorage.removeItem('rememberUser')
    // localStorage.removeItem('rememberFlag')
    
    // 使用 window.location.href 强制刷新页面，确保登录页面重新加载
    window.location.href = '/login'
}
function toggleCollapse() {
    emit('update:isCollapse', !props.isCollapse)
}
function toggleMobileMenu() {
    showMobileMenu.value = !showMobileMenu.value
}

function closeMobileMenu() {
    showMobileMenu.value = false
}

function navigateTo(path) {
    router.push(path)
    closeMobileMenu()
}

function goProfile() {
    router.push('/profile')
}


function openChangePasswordDialog() {
    // 通过全局事件触发用户管理页面的修改密码对话框
    window.dispatchEvent(new CustomEvent('open-change-password'))
}



</script>

<style scoped>
.navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 64px;
    padding: 0 32px;
    background: var(--bg-color) !important;
    color: var(--text-color);
    /* 只由 .main-header 控制 sticky，移除 sticky、top、z-index、box-shadow */
}

.navbar-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.collapse-btn {
    margin-right: 8px;
}

.navbar-breadcrumb {
    font-size: 16px;
}

.navbar-actions {
    display: flex;
    align-items: center;
    gap: 24px;
}

.navbar-badge {
    cursor: pointer;
}

.navbar-avatar {
    display: flex;
    align-items: center;
    cursor: pointer;
    outline: none;
    box-shadow: none;
    border: none;
}

.navbar-user-info {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 6px;
    transition: background-color 0.2s;
    outline: none;
    border: none;
}

.navbar-user-info:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

.navbar-user-info:focus {
    outline: none;
    border: none;
    box-shadow: none;
}

.el-dropdown:focus {
    outline: none !important;
    border: none !important;
    box-shadow: none !important;
}

.user-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2px;
}

.username {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-color);
    line-height: 1.2;
}

.roles {
    font-size: 11px;
    color: #666;
    line-height: 1.2;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    background: #f5f5f5;
    padding: 2px 6px;
    border-radius: 10px;
    border: 1px solid #e0e0e0;
    display: inline-block;
    font-weight: 400;
    transition: all 0.2s ease;
}

.role-admin {
    background: linear-gradient(135deg, #ff6b6b, #ee5a52);
    color: white;
    border-color: #ff6b6b;
    font-weight: 500;
    box-shadow: 0 1px 3px rgba(255, 107, 107, 0.3);
}

.role-user {
    background: linear-gradient(135deg, #74b9ff, #0984e3);
    color: white;
    border-color: #74b9ff;
    font-weight: 500;
    box-shadow: 0 1px 3px rgba(116, 185, 255, 0.3);
}

.role-default {
    background: linear-gradient(135deg, #a29bfe, #6c5ce7);
    color: white;
    border-color: #a29bfe;
    font-weight: 500;
    box-shadow: 0 1px 3px rgba(162, 155, 254, 0.3);
}
.notification-popover {
  min-height: 120px;
}
.notification-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
}
.notification-tabs span {
  flex: 1;
  text-align: center;
  padding: 8px 0;
  cursor: pointer;
  position: relative;
}
.notification-tabs .active {
  font-weight: bold;
  border-bottom: 2px solid #409EFF;
}
.tab-badge {
  margin-left: 4px;
  vertical-align: middle;
}
.notification-content {
  min-height: 60px;
  text-align: center;
  color: #888;
  padding: 16px 0;
}
.notification-footer {
  text-align: right;
  padding: 8px 0 0 0;
}
.notification-footer a {
  color: #409EFF;
  font-size: 13px;
  text-decoration: none;
}
.notice-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.notice-item {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px solid #f5f5f5;
  font-size: 14px;
}
.notice-title {
  color: #333;
}
.notice-time {
  color: #bbb;
  font-size: 12px;
}

/* 桌面端和移动端按钮显示控制 */
.desktop-only {
    display: block;
}

.mobile-only {
    display: none;
}

/* 移动端导航菜单样式 */
.mobile-nav-menu {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 2000;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
}

.mobile-nav-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
}

.mobile-nav-content {
    position: relative;
    width: 280px;
    height: 100vh;
    background: #fff;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    overflow-y: auto;
    z-index: 2001;
}

.mobile-nav-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 16px;
    border-bottom: 1px solid #f0f0f0;
    background: #f8f9fa;
}

.mobile-nav-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.mobile-nav-items {
    padding: 16px 0;
}

.mobile-nav-item {
    display: flex;
    align-items: center;
    padding: 16px 20px;
    cursor: pointer;
    transition: background-color 0.2s;
    border-bottom: 1px solid #f5f5f5;
}

.mobile-nav-item:hover {
    background: #f8f9fa;
}

.mobile-nav-item:active {
    background: #e9ecef;
}

.mobile-nav-item .el-icon {
    margin-right: 12px;
    font-size: 18px;
    color: #666;
    width: 20px;
    text-align: center;
}

.mobile-nav-item span {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .desktop-only {
        display: none !important;
    }
    
    .mobile-only {
        display: block !important;
    }
    
    .navbar {
        padding: 0 15px;
        flex-wrap: wrap;
        gap: 10px;
        background: var(--bg-color);
        border-bottom: 1px solid #e4e7ed;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1000;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    
    .navbar-left {
        flex: 1;
        min-width: 0;
        display: flex;
        align-items: center;
        gap: 15px;
    }
    
    .navbar-breadcrumb {
        font-size: 14px;
        font-weight: bold;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .navbar-actions {
        gap: 8px;
        display: flex;
        align-items: center;
    }
    
    .navbar-user-info {
        gap: 6px;
        display: flex;
        align-items: center;
    }
    
    .user-info {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        gap: 2px;
    }
    
    .username {
        font-size: 12px;
        font-weight: 500;
        color: var(--text-color);
        line-height: 1;
    }
    
    .roles {
        font-size: 10px;
        color: #999;
        line-height: 1;
    }
    
    .navbar-avatar {
        margin-right: 8px;
    }
    
    .navbar-badge {
        margin-right: 8px;
    }
    
    :deep(.el-popover) {
        width: 280px !important;
    }
    
    /* 添加移动端菜单按钮 */
    .mobile-menu-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 4px;
        background: transparent;
        border: none;
        cursor: pointer;
        color: var(--text-color);
    }
    
    .mobile-menu-btn:hover {
        background: #f5f7fa;
    }
}

@media (max-width: 480px) {
    .desktop-only {
        display: none !important;
    }
    
    .mobile-only {
        display: block !important;
    }
    
    .navbar {
        padding: 0 10px;
        gap: 5px;
        height: 50px;
    }
    
    .navbar-breadcrumb {
        font-size: 12px;
    }
    
    .navbar-actions {
        gap: 5px;
    }
    
    .navbar-badge {
        margin-right: 5px;
    }
    
    .navbar-avatar {
        margin-right: 5px;
    }
    
    .username {
        font-size: 11px;
    }
    
    .roles {
        font-size: 9px;
    }
    
    .mobile-nav-content {
        width: 260px;
    }
    
    .mobile-nav-header {
        padding: 16px 12px;
    }
    
    .mobile-nav-title {
        font-size: 14px;
    }
    
    .mobile-nav-item {
        padding: 14px 16px;
    }
    
    .mobile-nav-item .el-icon {
        font-size: 16px;
        margin-right: 10px;
    }
    
    .mobile-nav-item span {
        font-size: 13px;
    }
    
    :deep(.el-popover) {
        width: 250px !important;
    }
    
    .notification-popover {
        padding: 10px;
    }
    
    .notification-tabs {
        gap: 10px;
    }
    
    .notification-tabs span {
        font-size: 12px;
        padding: 6px 8px;
    }
}
</style>

<style>
:root {
  --bg-color: #ffffff;
  --text-color: #333333;
  --border-color: #e4e7ed;
}

body,
html,
#app {
  background: var(--bg-color) !important;
  color: var(--text-color) !important;
}

.el-main,
.main-content {
  background: var(--bg-color) !important;
}

.el-card,
.el-table,
.el-descriptions,
.el-form {
  background: var(--card-bg) !important;
  color: var(--text-color) !important;
  border-color: var(--border-color) !important;
  box-shadow: var(--shadow);
}

.el-dialog {
  background: #fff !important;
  color: var(--text-color) !important;
  border-color: var(--border-color) !important;
  box-shadow: var(--shadow);
}

.el-dialog__header {
  background: #fff !important;
  color: var(--text-color) !important;
}

.el-dialog__body {
  background: #fff !important;
  color: var(--text-color) !important;
}

.el-dialog__footer {
  background: #fff !important;
  color: var(--text-color) !important;
  border-top: none !important;
}

.el-menu,
.el-menu--vertical,
.sidebar {
  background: var(--sidebar-bg) !important;
  color: var(--sidebar-text) !important;
}

.el-menu-item.is-active,
.sidebar .el-menu-item.is-active,
.el-menu-item:hover {
  background: #363636 !important;
  color: #fff !important;
}

.el-header,
.main-header {
  background: var(--header-bg) !important;
  color: var(--text-color) !important;
  border-bottom: 1px solid var(--border-color) !important;
}

.el-input,
.el-textarea {
  background: var(--input-bg) !important;
  color: var(--text-color) !important;
  border-color: var(--input-border) !important;
}

.el-pagination {
  background: transparent !important;
  color: var(--text-color) !important;
}

/* 卡片与页面边缘、卡片之间的间距 */
.el-card {
  margin-bottom: 32px !important;
}

/* 让内容更有呼吸感 */
.el-main,
.main-content {
  padding: 12px 0 !important;
}

/* 对话框底部按钮区域样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}
</style>